#include <QMenu>
#include <QMouseEvent>
#include <QPainter>
#include <QPushButton>
#include <QHBoxLayout>

#include "dextitlebar.h"

DexTitleBar::DexTitleBar(QWidget *parent, Qt::WindowFlags f) : QFrame(parent, f)
	{
		minimizeBtn = new QPushButton(this);
		minimizeBtn->setObjectName("minimizeButton");

		restoreBtn = new QPushButton(this);
		restoreBtn->setObjectName("restoreButton");
		restoreBtn->setCheckable(true);

		closeBtn = new QPushButton(this);
		closeBtn->setObjectName("closeButton");

		layout = new QHBoxLayout(this);
		layout->setContentsMargins(0, 0, 3, 0);
		layout->setSpacing(1);
		layout->addStretch();
		layout->addWidget(minimizeBtn);
		layout->addWidget(restoreBtn);
		layout->addWidget(closeBtn);

		connect(closeBtn, SIGNAL(clicked()), this, SIGNAL(closeWindow()));
	}

void DexTitleBar::contextMenuEvent(QContextMenuEvent *event)
	{
		QMenu menu;
		menu.addAction(tr("Mi&nimize"), ((QWidget *)parent()), SLOT(showMinimized()));
		if (((QWidget *)parent())->windowState() == Qt::WindowMaximized)
			menu.addAction(tr("&Restore"), ((QWidget *)parent()), SLOT(showNormal()));
		else menu.addAction(tr("&Maximize"), ((QWidget *)parent()), SLOT(showMaximized()));
		menu.addSeparator();
		menu.addAction(tr("&Close"), ((QWidget *)parent()), SLOT(removeWindow()));
		menu.exec(event->globalPos());
	}

void DexTitleBar::mouseMoveEvent(QMouseEvent *event)
	{
		emit moveWindow(oldPos, event->globalPos());
		oldPos = event->globalPos();
	}

void DexTitleBar::mousePressEvent(QMouseEvent *event)
	{
		if (event->button() == Qt::LeftButton)
		{
			((QWidget *)parent())->raise();
			grabMouse(QCursor(Qt::ClosedHandCursor));
			oldPos = event->globalPos();
		}
	}

void DexTitleBar::mouseReleaseEvent(QMouseEvent *event)
	{
		Q_UNUSED(event);
		releaseMouse();
	}

void DexTitleBar::paintEvent(QPaintEvent *event)
	{
		QFrame::paintEvent(event);

		QPainter painter(this);
		painter.setRenderHint(QPainter::Antialiasing);
		painter.setFont(font());
		painter.setPen(Qt::black);
		painter.setOpacity(1.0);
		painter.drawText(3, 0, width(), height(), Qt::AlignLeft | Qt::AlignVCenter, windowTitle());
	}

void DexTitleBar::resizeEvent(QResizeEvent *event)
{
	QFrame::resizeEvent(event);
	QFrame *child = this->findChild<QFrame*>("frameTop");
	if (child != NULL)
		child->resize(width(), child->height());
}
